package com.qf.day02;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


class MyCache {
    //读写锁
    public static final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //独占锁
    //public static final Lock lock = new ReentrantLock();

    private Map<String, String> cache = new HashMap<>();

    /**
     * 写操作
     *
     *    必须要执行的 不见不散的锁
     *    可执行、可不执行 过期不候的锁
     * @param key
     * @param value
     */
    public void put(String key, String value) {
        Lock lock = readWriteLock.writeLock();
        lock.lock();//
        try {
            cache.put(key, value);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 读操作   private state = 0 --> 1  --> 2 --> 3  --> 2 --> 1 -->0
     * @param key
     */
    public void get(String key) {
        Lock lock = readWriteLock.readLock();
        try {
            lock.lock();
            String value = cache.get(key);
        } finally {
            lock.unlock();
        }
    }
}

/**
 * @author lixu
 */
public class MapDemo {


    public static void main(String[] args) {//主线程

        Map map = new ConcurrentHashMap();

        // java.util.ConcurrentModificationException
        //高并发
        for (int i = 0; i < 100; i++) {
            String s = String.valueOf(i);
            new Thread(() -> {//子线程   100个 几乎同时出发
                map.put(s, s);
                System.out.println(map);
            }).start();

        }


    }
}
